package ru.compscicenter.databases.zaikina.httpserver;

import ru.compscicenter.databases.zaikina.common.model.NodeConfig;

import java.io.*;
import java.net.Socket;

public class HttpSocketProcessor implements Runnable {
    private static final String SEARCH_PAGE = "html/search.html";
    private static final String INSERT_PAGE = "html/newFile.html";

    private Socket s;
    private InputStream is;
    private OutputStream os;
    private NodeConfig config;

    public HttpSocketProcessor() {}

    public HttpSocketProcessor(Socket s, NodeConfig config) throws IOException {
        this.s = s;
        this.is = s.getInputStream();
        this.os = s.getOutputStream();
        this.config = config;
    }

    public void run() {
        try {
            Command command = readInputHeaders();
            HttpCommandProcessor processor = new HttpCommandProcessor(command, config);
            writeResponse(processor.getResponse());
        } catch (IOException ex) {
            ex.printStackTrace();
            System.err.println("Unable to send data");
        } finally {
            try {
                s.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                System.err.println("Unable to close connection");
            }
        }
        System.err.println("Client processing finished");
    }

    private void writeResponse(String s) throws IOException {
        String response = "HTTP/1.1 200 OK\r\n" +
                "Server: YarServer/2009-09-09\r\n" +
                "Content-Type: text/html\r\n" +
                "Content-Length: " + s.length() + "\r\n" +
                "Connection: close\r\n\r\n";
        String result = response + s;
        os.write(result.getBytes());
        os.flush();
    }

    private Command readInputHeaders() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        int result = CommandTypes.DO_NOTHING;
        String answer = null;
        String s;
        while((s = br.readLine()) != null) {
            if (s.startsWith("GET") && s.contains("/search") && !s.contains("userInput")) {
                answer = SEARCH_PAGE;
                result = CommandTypes.SEND_PAGE;
            } else if (s.startsWith("GET") && s.contains("userInput")) {
                answer = getParam("userInput", s);
                result = CommandTypes.FIND_IN_BASE;
            } else if (s.startsWith("GET") && s.contains("keyWords")) {
                answer = getParam("keyWords", s);
                result = CommandTypes.GET_DOCUMENTS;
            } else if (s.startsWith("GET") && s.contains("/addNewFile") && !s.contains("uri")) {
                result = CommandTypes.SEND_PAGE;
                answer = INSERT_PAGE;
            } else if (s.startsWith("GET") && s.contains("uri")) {
                answer = getParam("uri", s);
                result = CommandTypes.INSERT_TO_BASE;
            }
            if(s.trim().length() == 0) {
                break;
            }
        }
        return new Command(result, answer);
    }

    private String getParam(String paramName, String where) {
        String key = "/" + paramName + "=";
        int idx = where.indexOf(key);

        if (idx != -1) {
            return where.substring(idx + key.length(), where.lastIndexOf(' '));
        }
        return null;
    }
}
